// VBConversions Note: VB project level imports
using System.Data;
using DevExpress.XtraEditors.Controls;
using System.Diagnostics;
using System.Xml.Linq;
using DevExpress.XtraEditors.Repository;
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Configuration;
using System.Collections;
using DevExpress.XtraEditors;
using System.Data.Sql;
using Microsoft.SqlServer;
using System.Windows.Forms;
using System;
using DevExpress.XtraReports;
using Microsoft.SqlServer.Management.Smo;
using DevExpress;
using System.Linq;
using System.IO;
// End of VB project level imports


namespace SCIEF.SysBFW.CommonExt
{
	namespace Utils
	{
		/// <summary>
		/// Class Helper to send email
		///
		/// How to use it:
		///
		/// Dim mail As EmailExt = New EmailExt(smtpMailServer)
		/// mail.From = fromAdr
		/// mail.To = toAdr
		/// mail.Cc = "aLeblanc@scief.com" ' ok zou....
		/// mail.Subject = "ERREUR LEWIS"
		/// mail.Body = ""
		/// mail.AddAttachment("C:\temp.txt")
		/// mail.SendMessage()
		///
		/// Optionnal Parameters
		///
		/// mail.Port Default 25
		/// mail.User
		/// mail.Password
		/// mail.Domain
		///
		/// </summary>
		/// <remarks></remarks>
		public class EmailExt
		{
			//
#region  Fields
			private string _server;
			private int _port = 25;
			private string _user;
			private string _password;
			private string _domain;
			private string _body;
			private string _subject;
			private string _from;
			private string _to;
			private string _cc;
			private string _bcc;
			//
			private System.Net.Mail.MailMessage _message;
			//
			private System.Net.Mail.SmtpClient smptpClient;
#endregion
			
#region  Properties
			/// <summary>
			/// Only one destination
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public string To
			{
				get
				{
					return _to;
				}
				set
				{
					_to = value;
				}
			}
			public string Bcc
			{
				get
				{
					return _bcc;
				}
				set
				{
					_bcc = value;
				}
			}
			public string Body
			{
				get
				{
					return _body;
				}
				set
				{
					_body = value;
				}
			}
			public string Cc
			{
				get
				{
					return _cc;
				}
				set
				{
					_cc = value;
				}
			}
			public string Domain
			{
				get
				{
					return _domain;
				}
				set
				{
					_domain = value;
				}
			}
			public string From
			{
				get
				{
					return _from;
				}
				set
				{
					_from = value;
				}
			}
			public System.Net.Mail.MailMessage Message
			{
				get
				{
					return _message;
				}
				set
				{
					_message = value;
				}
			}
			public string Password
			{
				get
				{
					return _password;
				}
				set
				{
					_password = value;
				}
			}
			public int Port
			{
				get
				{
					return _port;
				}
				set
				{
					_port = value;
				}
			}
			public string Server
			{
				get
				{
					return _server;
				}
				set
				{
					_server = value;
				}
			}
			public string Subject
			{
				get
				{
					return _subject;
				}
				set
				{
					_subject = value;
				}
			}
			public string User
			{
				get
				{
					return _user;
				}
				set
				{
					_user = value;
				}
			}
#endregion
			
#region  Methode
			public EmailExt()
			{
				this.Message = new System.Net.Mail.MailMessage();
			}
			/// <summary>
			/// Contructor with connection information
			/// </summary>
			/// <param name="server"></param>
			/// <param name="user"></param>
			/// <param name="password"></param>
			/// <param name="domain"></param>
			/// <remarks></remarks>
			public EmailExt(string server, string user = "", string password = "", string domain = "") : this()
			{
				this.Server = server;
				this.User = user;
				this.Password = password;
				this.Domain = domain;
			}
			/// <summary>
			/// Validate the filename and add it to the attachement collection of the messages
			/// </summary>
			/// <param name="filename"></param>
			/// <remarks></remarks>
			public void AddAttachment(string filename)
			{
				if (System.IO.File.Exists(filename))
				{
					this.Message.Attachments.Add(new System.Net.Mail.Attachment(filename, GetMIMEType(filename)));
				}
				else
				{
					throw (new FileNotFoundException(string.Format("File not found {0}", filename)));
				}
			}
			/// <summary>
			/// Go in the regestry to get the myme type of the file
			/// </summary>
			/// <param name="filepath"></param>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string GetMIMEType(string filepath)
			{
				System.Security.Permissions.RegistryPermission regPerm = new System.Security.Permissions.RegistryPermission(System.Security.Permissions.RegistryPermissionAccess.Read, "\\HKEY_CLASSES_ROOT");
				Microsoft.Win32.RegistryKey classesRoot = Microsoft.Win32.Registry.ClassesRoot;
				System.IO.FileInfo fi = new System.IO.FileInfo(filepath);
				string dotExt = fi.Extension.ToLower();
				Microsoft.Win32.RegistryKey typeKey = classesRoot.OpenSubKey("MIME\\Database\\Content Type");
				string Keyname = "";
				foreach (string key in typeKey.GetSubKeyNames())
				{
					Microsoft.Win32.RegistryKey curKey = classesRoot.OpenSubKey("MIME\\Database\\Content Type\\" + key);
					if (System.Convert.ToString(curKey.GetValue("Extension")) == dotExt)
					{
						Keyname = Keyname;
					}
				}
				return Keyname;
			}
			/// <summary>
			/// Construct the message information and send it.
			/// </summary>
			/// <remarks></remarks>
			public void SendMessage()
			{
				try
				{
					smptpClient = new System.Net.Mail.SmtpClient(this.Server, this.Port);
					smptpClient.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(smptpClient_SendCompleted);
					smptpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
					//smptpClient.Credentials....Maybe this way .......BD 2011-12-19
					//
					if (!string.IsNullOrEmpty(this.User) && !string.IsNullOrEmpty(this.Password))
					{
						System.Net.NetworkCredential credential = new System.Net.NetworkCredential(this.User, this.Password);
						if (!string.IsNullOrEmpty(this.Domain))
						{
							credential.Domain = this.Domain;
						}
						smptpClient.Credentials = credential;
					}
					//
					this.Message.From = new System.Net.Mail.MailAddress(this.From);
					this.Message.To.Add(this.To);
					//Me.Message.ReplyTo = New System.Net.Mail.MailAddress(Me.From)
					this.Message.Subject = this.Subject;
					this.Message.Body = this.Body;
					//
					if (!string.IsNullOrEmpty(this.Cc))
					{
						this.Message.CC.Add(this.Cc);
					}
					if (!string.IsNullOrEmpty(this.Bcc))
					{
						this.Message.Bcc.Add(this.Bcc);
					}
					//Fonctionne pas tjrs.... Ex: relais.videoron.ca
					//smptpClient.SendAsync(Me.Message, Me)
					smptpClient.Send(this.Message);
				}
				catch (Exception ex)
				{
					throw (new Exception(string.Format("Error in Sendmessage with subject {0}, using server {1}{2}{2}{2}{3}", this.Subject, this.Server, "\r\n", ex.Message), ex));
				}
			}
			/// <summary>
			/// This sub is call by the SendAsync when finish.
			/// </summary>
			/// <param name="sender"></param>
			/// <param name="e"></param>
			/// <remarks></remarks>
			private void smptpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
			{
				EmailExt exMail = (EmailExt) e.UserState;
				if (e.Cancelled)
				{
					throw (new OperationCanceledException(string.Format("Operation cancelled. Message with subject {0}", exMail.Message.Subject)));
				}
				//
				if (e.Error != null)
				{
					throw (new Exception(string.Format("An error occur {0}. Message With Subject {1}", e.Error.Message, exMail.Message.Subject), e.Error));
				}
			}
#endregion
		}
	}
	
}
